home *** CD-ROM | disk | FTP | other *** search
/ Night Owl 6 / Night Owl's Shareware - PDSI-006 - Night Owl Corp (1990).iso / 016a / gofer221.zip / CH09 < prev    next >
Text File  |  1991-11-20  |  38KB  |  1,057 lines

  1.  
  2.  
  3. Introduction to Gofer         9. MORE ABOUT VALUE DECLARATIONS                  
  4.  
  5.  
  6. 9. MORE ABOUT VALUE DECLARATIONS
  7.  
  8. 9.1  Simple pattern matching
  9. ----------------------------
  10. Although the Gofer standard prelude includes many useful functions, you
  11. will usually need to define a collection of new functions for  specific
  12. problems and calculations.  The declaration of a function  "f"  usually
  13. takes the form of a number of equations of the form:
  14.  
  15.             f <pat1> <pat2> ... <patn>  =   <rhs>
  16.  
  17. (or an equivalent expression, if "f"  is  written  as  by  an  operator
  18. symbol).   Each  of  the  expressions  <pat1>,  <pat2>,   ...,   <patn>
  19. represents an argument to the function "f" and is called  a  `pattern'.
  20. The number of such arguments is called the arity of  "f".   If  "f"  is
  21. defined by more than one equation then they must  be  entered  together
  22. and each one must give the same arity for "f".
  23.  
  24. When a function is defined by more than one equation, it  will  usually
  25. be necessary to evaluate one or more of the arguments to  the  function
  26. to  determine  which  equation  applies.   This   process   is   called
  27. `pattern-matching'.  In all of the previous examples we have used  only
  28. the simplest kind of pattern -- a variable.  As  an  example,  consider
  29. the factorial function defined in section 5:
  30.  
  31.     fact n = product [1..n]
  32.  
  33. If we then wish to evaluate the expression "fact 6" we first match  the
  34. expression "6" against the pattern "n" and then evaluate the expression
  35. obtained from "product [1..n]" by replacing the variable "n"  with  the
  36. expression "6".  The process of matching the arguments  of  a  function
  37. against the patterns in its definition and obtaining another expression
  38. to be evaluated is called a `reduction'.  Using Gofer, it  is  easy  to
  39. verify that the evaluation of "fact 6" takes one  more  reduction  than
  40. that of "product [1..6]":
  41.  
  42.     ? fact 6
  43.     720
  44.     (57 reductions, 85 cells)
  45.     ? product [1..6]
  46.     720
  47.     (56 reductions, 85 cells)
  48.     ? 
  49.  
  50. Many kinds of constants such as the boolean values True and  False  can
  51. also be used in  patterns,  as  in  the  following  definition  of  the
  52. function "not" taken from the standard prelude:
  53.  
  54.     not True  = False
  55.     not False = True
  56.  
  57. In order to determine the value of an expression of the form  "not  b",
  58. we must first evaluate the expression "b".  If  the  result  is  "True"
  59. then we use the first equation  and  the  value  of  "not  b"  will  be
  60. "False".  If the value of "b" is "False", then the second  equation  is
  61. used and the value of "not b" will be "True".
  62.  
  63.  
  64.                                       21
  65.  
  66.  
  67.  
  68.  
  69. Introduction to Gofer         9.1  Simple pattern matching                      
  70.  
  71.  
  72. Other constants, including integers, characters and strings may also be
  73. used in patterns.  For example, if we define a function "hello" by:
  74.  
  75.     hello "Mark"  =  "Howdy"
  76.     hello name    =  "Hello " ++ name ++ ", nice to meet you!"
  77.  
  78. then:
  79.  
  80.     ? hello "Mark"
  81.     Howdy
  82.     (1 reduction, 12 cells)
  83.     ? hello "Fred"
  84.     Hello Fred, nice to meet you!
  85.     (13 reductions, 66 cells)
  86.     ?
  87.  
  88. Note that the  order  in  which  the  equations  are  written  is  very
  89. important because Gofer always uses the first applicable equation.   If
  90. instead we had defined the function with the equations:
  91.  
  92.     hello name    =  "Hello " ++ name ++ ", nice to meet you!"
  93.     hello "Mark"  =  "Howdy"
  94.  
  95. then the results obtained using this function would have been a  little
  96. different:
  97.  
  98.     ? hello "Mark"
  99.     Hello Mark, nice to meet you!
  100.     (13 reductions, 66 cells)
  101.     ? hello "Fred"
  102.     Hello Fred, nice to meet you!
  103.     (13 reductions, 66 cells)
  104.     ?
  105.  
  106. There are a number of other useful kinds of pattern, some of which  are
  107. illustrated by the following examples:
  108.  
  109.   o  Wildcard:       _        matches  any value  at all;  it is like a
  110.                               variable pattern, except that there is no
  111.                               way of referring to the matched value.
  112.  
  113.   o  Tuples:         (x,y)    matches a  pair  whose  first  and second
  114.                               elements are called x and y respectively.
  115.  
  116.   o  Lists:          [x]      matches a list with precisely one element
  117.                               called x.
  118.                      [_,2,_]  matches  a   list  with   precisely three
  119.                               elements,  the  second  of  which  is the
  120.                               integer 2.
  121.                      []       matches the empty list.
  122.                      (x:xs)   matches a non-empty  list with head x and
  123.                               tail xs.
  124.  
  125.   o  As patterns:    p@(x,y)  matches a  pair  whose  first and  second
  126.                               components  are  called  x  and  y.   The
  127.                               complete pair can  also  be  referred  to
  128.  
  129.  
  130.                                       22
  131.  
  132.  
  133.  
  134.  
  135. Introduction to Gofer         9.1  Simple pattern matching                      
  136.  
  137.  
  138.                               directly as p.
  139.  
  140.   o  (n+k) patterns: (m+1)    matches an integer value  greater than or
  141.                               equal to 1.  The value referred to by the
  142.                               variable m is one  less  than  the  value
  143.                               matched.
  144.  
  145. A further kind of pattern (called an irrefutable pattern) is introduced
  146. in section 9.11.
  147.  
  148. Note that no variable name can be used more than once on the left  hand
  149. side of each equation in a function definition.  The following example:
  150.  
  151.     areTheyTheSame x x = True 
  152.     areTheyTheSame _ _ = False 
  153.  
  154. will not be accepted by the Gofer system, but should instead be defined
  155. using the notation of guards introduced in the next section:
  156.  
  157.     areTheyTheSame x y
  158.             | x==y      = True
  159.             | otherwise = False
  160.  
  161.  
  162. 9.2  Guarded equations
  163. ----------------------
  164. Each of the equations in a function  definition  may  contain  `guards'
  165. which require certain conditions  on  the  values  of  the  functions's
  166. arguments to be met.  As an example, here is a function which uses  the
  167. standard prelude function even :: Int -> Bool to determine whether  its
  168. argument is an even integer or not, and returns the  string  "even"  or
  169. "odd" as appropriate:
  170.  
  171.     oddity n | even n    = "even"
  172.              | otherwise = "odd"
  173.  
  174. In general, an equation using guards takes the form:
  175.  
  176.     f x1 x2 ... xn | condition1  =  e1
  177.                    | condition2  =  e2
  178.                    .
  179.                    . 
  180.                    | conditionm  =  em
  181.  
  182. This equation is used by evaluating each  of  the  conditions  in  turn
  183. until one of them evaluates to "True", in which case the value  of  the
  184. function is given by the corresponding expression e on the  right  hand
  185. side of the `=' sign.  In Gofer, the variable "otherwise" is defined to
  186. be equal to "True", so that writing "otherwise" as the condition  in  a
  187. guard means that the corresponding expression will always be used if no
  188. previous guard has been satisfied.
  189.  
  190. [ASIDE: in the notation of [1], the above examples would be written as:
  191.  
  192.     oddity n        =  "even",   if even n
  193.                     =  "odd",    otherwise
  194.  
  195.  
  196.                                       23
  197.  
  198.  
  199.  
  200.  
  201. Introduction to Gofer         9.2  Guarded equations                            
  202.  
  203.  
  204.     f x1 x2 ... xn  = e1,     if condition1
  205.                     = e2,     if condition2
  206.                       .
  207.                       .
  208.                     = em,     if conditionm
  209.  
  210. Translation between the two notations is relatively straightforward.]
  211.  
  212.  
  213. 9.3  Local definitions
  214. ----------------------
  215. Function definitions may include local definitions for variables  which
  216. can be used both in guards and on the right hand side of  an  equation.
  217. Consider the following function which calculates the number of distinct
  218. real roots for a quadratic equation of the form a*x*x + b*x + c = 0:
  219.  
  220.     numberOfRoots a b c | discr>0   =  2
  221.                         | discr==0  =  1
  222.                         | discr<0   =  0
  223.                           where discr = b*b - 4*a*c
  224.  
  225. [ASIDE: The operator (==) is used to test whether two values are  equal
  226. or not.  You should take care not to confuse this with the  single  `='
  227. sign used in function definitions].
  228.  
  229. Local definitions can also be introduced at an arbitrary  point  in  an
  230. expression using an expression of the form:
  231.  
  232.                   let <decls> in <expr>
  233.  
  234. For example:
  235.  
  236.     ? let x = 1 + 4 in x*x + 3*x + 1
  237.     41
  238.     (8 reductions, 15 cells)
  239.     ? let p x = x*x + 3*x + 1  in  p (1 + 4)
  240.     41
  241.     (7 reductions, 15 cells)
  242.     ?
  243.  
  244.  
  245. 9.4  Recursion with integers
  246. ----------------------------
  247. Recursion  is  a  particularly  important  and  powerful  technique  in
  248. functional programming which is useful for defining functions involving
  249. a wide range of datatypes.  In this section, we describe one particular
  250. application of recursion to give  an  alternative  definition  for  the
  251. factorial function from section 5.
  252.  
  253. Suppose that we wish to calculate the factorial of a given  integer  n.
  254. We can split the problem up into two special cases:
  255.  
  256.   o  If n is zero then the value of n! is 1.
  257.  
  258.   o  Otherwise, n!  = 1 * 2 * ... * (n-1) * n = (n-1)! * n  and  so  we
  259.      can calculate the value of n! by calculating the value  of  (n-1)!
  260.  
  261.  
  262.                                       24
  263.  
  264.  
  265.  
  266.  
  267. Introduction to Gofer         9.4  Recursion with integers                      
  268.  
  269.  
  270.      and then multiplying it by n.
  271.  
  272. This process can be expressed directly in  Gofer  using  a  conditional
  273. expression:
  274.  
  275.     fact1 n  =  if n==0 then 1 else n * fact1 (n-1)
  276.  
  277. This definition may seem rather circular; in  order  to  calculate  the
  278. value of n!, we must first calculate (n-1)!, and unless n  is  1,  this
  279. requires the calculation of (n-2)! etc...  However, if  we  start  with
  280. some positive value for the variable n, then we will  eventually  reach
  281. the case where the value of 0! is required -- and this does not require
  282. any further calculation.  The following diagram illustrates how  6!  is
  283. evaluated using "fact1":
  284.  
  285.     fact1 6  ==>  6 * fact1 5
  286.              ==>  6 * (5 * fact1 4)
  287.              ==>  6 * (5 * (4 * fact1 3))
  288.              ==>  6 * (5 * (4 * (3 * fact1 2)))
  289.              ==>  6 * (5 * (4 * (3 * (2 * fact1 1))))
  290.              ==>  6 * (5 * (4 * (3 * (2 * (1 * fact1 0)))))
  291.              ==>  6 * (5 * (4 * (3 * (2 * (1 * 1)))))
  292.              ==>  6 * (5 * (4 * (3 * (2 * 1))))
  293.              ==>  6 * (5 * (4 * (3 * 2)))
  294.              ==>  6 * (5 * (4 * 6))
  295.              ==>  6 * (5 * 24)
  296.              ==>  6 * 120
  297.              ==>  720
  298.  
  299. Incidentally, there are several other ways  of  writing  the  recursive
  300. definition of "fact1" above in Gofer.  For example, using guards:
  301.  
  302.     fact2 n
  303.       | n==0        =  1
  304.       | otherwise   =  n * fact2 (n-1)
  305.  
  306. or using pattern matching with an integer constant:
  307.  
  308.     fact3 0         =  1
  309.     fact3 n         =  n * fact3 (n-1)
  310.  
  311. Which of these you use is largely a matter of personal taste.
  312.  
  313. Yet another style of definition uses the (n+k)  patterns  mentioned  in
  314. section 9.1:
  315.  
  316.     fact4 0         =  1
  317.     fact4 (n+1)     =  (n+1) * fact4 n
  318.  
  319. which is equivalent to:
  320.  
  321.     fact5 n | n==0  =  1
  322.             | n>=1  =  n * fact5 (n-1)
  323.  
  324. [COMMENT: Although each of the above definitions gives the same  result
  325. as the original "fact" function  for  each  non-negative  integer,  the
  326.  
  327.  
  328.                                       25
  329.  
  330.  
  331.  
  332.  
  333. Introduction to Gofer         9.4  Recursion with integers                      
  334.  
  335.  
  336. functions can still be distinguished by the values obtained  when  they
  337. are applied to negative integers:
  338.  
  339.   o  "fact (-1)" evaluates to the integer 1.
  340.   o  "fact1 (-1)" causes Gofer to enter an infinite loop, which is only
  341.      eventually terminated when Gofer runs out of `stack space'.
  342.   o  "fact4 (-1)" causes an evaluation error and prints the
  343.       message {fact4 (-1)} on the screen.
  344.  
  345. To most people, this suggests that the definition of "fact4" is perhaps
  346. preferable to that of either "fact" or "fact1" as it neither gives  the
  347. wrong answer  without  allowing  this  to  be  detected  nor  causes  a
  348. potentially non-terminating computation.]
  349.  
  350.  
  351. 9.5  Recursion with lists
  352. -------------------------
  353. The same kind of  technique  that  can  be  used  to  define  recursive
  354. functions with integers can also be used to define recursive  functions
  355. on lists.  As an example, suppose that we wish to define a function  to
  356. calculate the length of  a  list.   As  the  standard  prelude  already
  357. includes such a function called "length", we  will  call  the  function
  358. developed here "len" to avoid any conflict.  Now suppose that  we  wish
  359. to find the length of a given list.  There are two cases to consider:
  360.  
  361.   o  If the list is empty then it has length 0
  362.  
  363.   o  Otherwise, it is non-empty and can be written in the  form  (x:xs)
  364.      for some element x and some list xs.  Thus the  original  list  is
  365.      one element longer than xs, and so has length 1 + len xs.
  366.  
  367. Writing these two cases out leads directly to the following definition:
  368.  
  369.     len []      =  0
  370.     len (x:xs)  =  1 + length xs
  371.  
  372. The following diagram illustrates the way that  this  function  can  be
  373. used to determine the length of the list [1,2,3,4] (remember that  this
  374. is just an abbreviation for 1 : 2 : 3 : 4 : []):
  375.  
  376.     len [1,2,3,4]  ==>  1 + len [2,3,4]
  377.                    ==>  1 + (1 + len [3,4])
  378.                    ==>  1 + (1 + (1 + len [4]))
  379.                    ==>  1 + (1 + (1 + (1 + len [])))
  380.                    ==>  1 + (1 + (1 + (1 + 0)))
  381.                    ==>  1 + (1 + (1 + 1))
  382.                    ==>  1 + (1 + 2)
  383.                    ==>  1 + 3
  384.                    ==>  4
  385.  
  386. As  further  examples,  you  might  like  to  look  at  the   following
  387. definitions which use similar ideas to define the functions product and
  388. map introduced in earlier sections:
  389.  
  390.     product []     = 1
  391.     product (x:xs) = x * product xs
  392.  
  393.  
  394.                                       26
  395.  
  396.  
  397.  
  398.  
  399. Introduction to Gofer         9.5  Recursion with lists                         
  400.  
  401.  
  402.     map f []      =  []
  403.     map f (x:xs)  =  f x : map f xs
  404.  
  405.  
  406. 9.6  Lazy evaluation
  407. --------------------
  408. Gofer evaluates expressions using a technique  sometimes  described  as
  409. `lazy evaluation' which means that:
  410.  
  411.   o  No expression is evaluated until its value is needed.
  412.  
  413.   o  No  shared  expression  is  evaluated  more  than  once;  if   the
  414.      expression is ever evaluated then the result is shared between all
  415.      those places in which it is used.
  416.  
  417. The first of these ideas is illustrated by the following function:
  418.  
  419.     ignoreArgument x = "I didn't need to evaluate x"
  420.  
  421. Since the result of the function "ignoreArgument" doesn't depend on the
  422. value of its argument "x", that argument will not be evaluated:
  423.  
  424.     ? ignoreArgument (1/0)
  425.     I didn't need to evaluate x
  426.     (1 reduction, 31 cells)
  427.     ?
  428.  
  429. In some situations, it is useful to be able to force Gofer to  evaluate
  430. the argument to a function before the function is applied.  This can be
  431. achieved using the function "strict" defined in the  standard  prelude;
  432. An expression of the form "strict f x" is evaluated by first evaluating
  433. the argument "x" and then applying the function "f" to the result:
  434.  
  435.     ? strict ignoreArgument (1/0)
  436.     {primDivInt 1 0}
  437.     (4 reductions, 29 cells)
  438.     ?
  439.  
  440. The second  basic  idea  behind  lazy  evaluation  is  that  no  shared
  441. expression should be  evaluated  more  than  once.   For  example,  the
  442. following two expressions can be used to calculate 3*3*3*3:
  443.  
  444.     ? square * square where square = 3 * 3
  445.     81
  446.     (3 reductions, 9 cells)
  447.     ? (3 * 3) * (3 * 3)
  448.     81
  449.     (4 reductions, 11 cells)
  450.     ?
  451.  
  452. Notice that the first expression requires one less reduction  than  the
  453. second.  Excluding the single reduction step  needed  to  convert  each
  454. integer into a string, the sequences of reductions that will be used in
  455. each case are as follows:
  456.  
  457.  
  458.  
  459.  
  460.                                       27
  461.  
  462.  
  463.  
  464.  
  465. Introduction to Gofer         9.6  Lazy evaluation                              
  466.  
  467.  
  468.     square * square where square = 3 * 3
  469.        -- calculate the value of square by reducing 3 * 3 ==> 9
  470.        -- and replace each occurrence of square with this result
  471.        ==> 9 * 9
  472.        ==> 81
  473.  
  474.     (3 * 3) * (3 * 3)   -- evaluate first (3 * 3)
  475.        ==> 9 * (3 * 3)  -- evaluate second (3 * 3)
  476.        ==> 9 * 9
  477.        ==>
  478.  
  479. Lazy evaluation is a very powerful feature of programming in a language
  480. like Gofer, and means that only the minimum amount  of  calculation  is
  481. used to determine the result of an expression.  The  following  example
  482. is often used to illustrate this point.
  483.  
  484. Consider the task  of  finding  the  smallest  element  of  a  list  of
  485. integers.  The standard prelude includes a function "minimum" which can
  486. be used for this very purpose:
  487.  
  488.     ? minimum [100,99..1]
  489.     1
  490.     (809 reductions, 1322 cells)
  491.     ?
  492.  
  493. (The expression [100,99..1] denotes the list of integers from 1 to  100
  494. arranged in decreasing order, as described in section 10.1).
  495.  
  496. A rather different approach involves sorting the elements of  the  list
  497. into increasing  order  (using  the  function  "sort"  defined  in  the
  498. standard prelude) and  then  take  the  element  at  the  head  of  the
  499. resulting list  (using  the  standard  function  "head").   Of  course,
  500. sorting the list in its entirity is  likely  to  require  significantly
  501. more work than the previous approach:
  502.  
  503.     ? sort [100,99..1]
  504.     [1, 2, 3, 4, 5, 6, 7, 8, ... etc ..., 99, 100]
  505.     (10712 reductions, 21519 cells)
  506.     ?
  507.  
  508. However, thanks to lazy-evaluation, calculating just the first  element
  509. of the sorted list actually requires less work in this particular  case
  510. than the first solution using "minimum":
  511.  
  512.     ? head (sort [100,99..1])
  513.     1
  514.     (713 reductions, 1227 cells)
  515.     ?
  516.  
  517. Incidentally, it is  probably  work  pointing  out  that  this  example
  518. depends rather heavily on the particular algorithm  used  to  "sort"  a
  519. list of elements.  The results are rather different if we  compare  the
  520. same two approaches used to calculate the maximum value in the list:
  521.  
  522.     ? maximum [100,99..1]
  523.     100
  524.  
  525.  
  526.                                       28
  527.  
  528.  
  529.  
  530.  
  531. Introduction to Gofer         9.6  Lazy evaluation                              
  532.  
  533.  
  534.     (812 reductions, 1225 cells)
  535.     ? last (sort [100,99..1])
  536.     100
  537.     (10612 reductions, 20732 cells)
  538.     ?
  539.  
  540. This difference is caused by the fact that each  element  in  the  list
  541. produced by "sort" is  only  known  once  the  values  of  all  of  the
  542. preceding elements are also known.  Thus  the  complete  list  must  be
  543. sorted in order to obtain the last element.
  544.  
  545.  
  546. 9.7  Infinite data structures
  547. -----------------------------
  548. One particular benefit of lazy evaluation is that it makes it  possible
  549. for functions  in  Gofer  to  manipulate  `infinite'  data  structures.
  550. Obviously we cannot hope to  either  construct  or  store  an  infinite
  551. object in its entirity -- the advantage of lazy evaluation is  that  it
  552. allows us to construct infinite objects piece  by  piece  as  necessary
  553. (and to reuse the storage space used by parts of the object  when  they
  554. are no longer required).
  555.  
  556. As a simple example, consider the following function which can be  used
  557. to produce infinite lists of integer values:
  558.  
  559.     countFrom n = n : countFrom (n+1)
  560.  
  561. If we evaluate the expression "countFrom 1", Gofer just prints the list
  562. of integer values beginning with 1 until it is interrupted.  Once  each
  563. element in the list has been printed, the storage  used  to  hold  that
  564. element can be reused to hold later elements in the  list.   Evaluating
  565. this expression is equivalent to using an `infinite' loop to print  the
  566. list of integers in an imperative programming language:
  567.  
  568.     ? countFrom 1
  569.     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,^C{Interrupted!}
  570.     (53 reductions, 160 cells)
  571.     ?
  572.  
  573. For practical applications, we are usually only interested in  using  a
  574. finite portion of an infinite data  structure  (just  as  loops  in  an
  575. imperative programming language are usually terminated  after  finitely
  576. many iterations).  For example, using  "countFrom"  together  with  the
  577. function "take" defined in the standard  prelude,  we  can  repeat  the
  578. calculation from section 4 to find the sum of the integers 1 to 10:
  579.  
  580.     ? sum (take 10 (countFrom 1))
  581.     55
  582.     (62 reductions, 119 cells)
  583.     ?
  584.  
  585. [ASIDE: The expression "take n xs" evaluates to a list  containing  the
  586. first n elements of the list xs (or to xs itself if the  list  contains
  587. fewer than n elements).  Thus "countFrom 1" generates the infinite list
  588. of integers, "take 10" ensures that only the  first  ten  elements  are
  589. calculated, and "sum" calculates the sum of those integers as before.]
  590.  
  591.  
  592.                                       29
  593.  
  594.  
  595.  
  596.  
  597. Introduction to Gofer         9.7  Infinite data structures                     
  598.  
  599.  
  600. A particular advantage of using infinite data  structures  is  that  it
  601. enables us to describe an object without being tied to  one  particular
  602. application of that object.  Consider the following definition for  the
  603. infinite list of powers of two [1, 2, 4, 8, ...]:
  604.  
  605.     powersOfTwo = 1 : map double powersOfTwo 
  606.                   where double n = 2*n
  607.  
  608. This list be used in a variety of ways; using the operator (!!) defined
  609. in the standard prelude [xs!!n evaluates to the nth element of the list
  610. xs], we can define a function to find the nth power of 2 for  an  given
  611. integer n:
  612.  
  613.     twoToThe n = powersOfTwo !! n 
  614.  
  615. Alternatively, we can use the list "powersOfTwo" to define  a  function
  616. mapping lists of  bits  (represented  by  integers  0  and  1)  to  the
  617. corresponding decimal number: simply reverse the order of  the  digits,
  618. multiply each by the corresponding power of two and calculate the  sum.
  619. Using functions from the standard  prelude,  this  translates  directly
  620. into the definition:
  621.  
  622.     binToDec ds = sum (zipWith (*) (reverse ds) powersOfTwo)
  623.  
  624. For example:
  625.  
  626.     ? twoToThe 12
  627.     4096
  628.     (15 reductions, 21 cells)
  629.     ? binToDec [1,0,1,1,0]
  630.     22
  631.     (40 reductions, 85 cells)
  632.     ?
  633.  
  634. 9.8  Polymorphism
  635. -----------------
  636. Given the definition of "product" in section 9.5, it  is  easy  to  see
  637. that product takes a single argument which is a list  of  integers  and
  638. returns a single integer value -- the product of the  elements  of  the
  639. list.  In other words, "product" has type [Int] -> Int.  On  the  other
  640. hand, it is not immediately clear what the type of the  function  "map"
  641. should be.  Clearly the first argument of "map" must be a function  and
  642. both the second argument and the result are lists, so that the type  of
  643. "map" must be of the form:
  644.  
  645.              (a -> b)   ->      [c]      ->     [d]
  646.              \______/          \___/           \___/
  647.            type of 1st      type of 2nd      type of result
  648.            argument "f"     argument "xs"    "map f xs"
  649.  
  650. But what can be said about the types a, b, c and  d?   One  possibility
  651. would be to choose a = b = c = d = Int which would  be  acceptable  for
  652. expressions such as  "map  fact  [1,2,3,4]",  but  this  would  not  be
  653. suitable in an expression such as  "map  chr  [65,75,32]"  because  the
  654. "chr" function does not have type Int -> Int.
  655.  
  656.  
  657.  
  658.                                       30
  659.  
  660.  
  661.  
  662.  
  663. Introduction to Gofer         9.8  Polymorphism                                 
  664.  
  665.  
  666. Notice however that the argument type of "f" must be the  same  as  the
  667. type of elements in the second argument (i.e.  a  =  c)  since  "f"  is
  668. applied to each element in that list.  Similarly, the  result  type  of
  669. "f" must be the same as the type of elements in the result list (i.e. b
  670. = d) since each element in  this  list  is  obtained  as  a  result  of
  671. applying the function "f" to some value.  It is therefore reasonable to
  672. treat the "map" function as having any type of the form:
  673.  
  674.                   (a -> b)  ->  [a]  ->  [b]
  675.  
  676. The letters  "a"  and  "b"  used  in  this  type  expression  represent
  677. arbitrary types and are called type variables.  An  object  whose  type
  678. includes one or more type variables can be thought of  as  having  many
  679. different types and is often described as having a  `polymorphic  type'
  680. (literally: its type has `many shapes').
  681.  
  682. The ability to define and use polymorphic functions in Gofer turns  out
  683. to be very useful.  Here are the types of some of the other polymorphic
  684. functions which have been used in previous  examples  which  illustrate
  685. this point:
  686.  
  687.     length :: [a] -> Int
  688.     (++)   :: [a] -> [a] -> [a]
  689.     concat :: [[a]] -> [a]
  690.  
  691. Thus we can use precisely the same "length" function to determine  both
  692. the length of a list of integers as well as finding  the  length  of  a
  693. string:
  694.  
  695.     ? length [1..10]
  696.     10
  697.     (98 reductions, 138 cells)
  698.     ? length "Hello"
  699.     5
  700.     (22 reductions, 36 cells)
  701.     ? 
  702.  
  703.  
  704. 9.9  Higher-order functions
  705. ---------------------------
  706. In Gofer, function values are treated in much the same way as any other
  707. kind of value; in particular, they can be used both  as  arguments  to,
  708. and results of other functions.
  709.  
  710. Functions which manipulate  other  functions  in  this  way  are  often
  711. described as `higher-order functions'.  Consider the following example,
  712. taken from the standard prelude:
  713.  
  714.     (.)       :: (b -> c) -> (a -> b) -> (a -> c)
  715.     (f . g) x  = f (g x)
  716.  
  717. As indicated by the type declaration, we think of the (.) operator as a
  718. function taking two function arguments and returning  another  function
  719. value as its result.  If f and  g  are  functions  of  the  appropriate
  720. types, then (f . g) is a function called the composition of f  with  g.
  721. Applying (f . g) to a value is equivalent to applying g to that  value,
  722.  
  723.  
  724.                                       31
  725.  
  726.  
  727.  
  728.  
  729. Introduction to Gofer         9.9  Higher-order functions                       
  730.  
  731.  
  732. and then applying f to the result [As described, far  more  eloquently,
  733. by the second line of the declaration above!].
  734.  
  735. Many problems can often be described very elegantly as a composition of
  736. other functions.  Consider the problem of calculating the total  number
  737. of characters used in a list of strings.  A simple  recursive  function
  738. provides one solution:
  739.  
  740.     countChars []     = 0
  741.     countChars (w:ws) = length w + countChars ws 
  742.  
  743.     ? countChars ["super","cali","fragi","listic"]
  744.     20
  745.     (96 reductions, 152 cells)
  746.     ?
  747.  
  748. An alternative approach is to notice that we can  calculate  the  total
  749. number of characters by  first  combining  all  of  the  words  in  the
  750. argument list into a single word (using concat) and  then  finding  the
  751. length of that word:
  752.  
  753.     ? (length . concat) ["super","cali","fragi","listic"]
  754.     20
  755.     (113 reductions, 211 cells)
  756.     ?
  757.  
  758. Another solution is to first find the length of each word in  the  list
  759. (using the "map" function to apply "length"  to  each  word)  and  then
  760. calculate the sum of these individual lengths:
  761.  
  762.     ? (sum . map length) ["super","cali","fragi","listic"]
  763.     20
  764.     (105 reductions, 172 cells)
  765.     ?
  766.  
  767.  
  768. 9.10 Variable declarations
  769. --------------------------
  770. A variable declaration  is  a  special  form  of  function  definition,
  771. almost always consisting of a single equation of the form:
  772.  
  773.                            var = rhs
  774.  
  775. (i.e. a function declaration of arity 0).  Whereas the  values  defined
  776. by function declarations of arity>0 are guaranteed to be functions, the
  777. values defined by variable declarations may or may not be functions:
  778.  
  779.     odd = not . even   -- if an integer is not even then it must be odd
  780.     val = sum [1..100]
  781.  
  782. Note that variables defined like this at the top level  of  a  file  of
  783. definitions will be evaluated using lazy evaluation.  The first time we
  784. refer  to  the  variable  "val"  defined  above  (either  directly   or
  785. indirectly), Gofer evaluates the sum of the integers from 1 to 100  and
  786. overwrites the definition of "val" with this number.  This  calculation
  787. can then be avoided for each subsequent use of "val" (unless  the  file
  788.  
  789.  
  790.                                       32
  791.  
  792.  
  793.  
  794.  
  795. Introduction to Gofer         9.10 Variable declarations                        
  796.  
  797.  
  798. containing the definition of "val" is reloaded).
  799.  
  800.     ? val
  801.     5050
  802.     (809 reductions, 1120 cells)
  803.  
  804.     ? val
  805.     5050
  806.     (1 reduction, 7 cells)
  807.  
  808.     ?
  809.  
  810. Because of this behaviour, should probably try to avoid using  variable
  811. declarations where the resulting value will require a  lot  of  storage
  812. space.  If we load a file of definitions including the line:
  813.  
  814.     longList = [1..10000]
  815.  
  816. and  then  evaluate  the  expression  "length   longList"   (eventually
  817. obtaining the expected result of 10000), then Gofer will  evaluate  the
  818. definition of "longList" and replace  it  with  the  complete  list  of
  819. integers from  1  upto  10000.   Unlike  other  memory  used  during  a
  820. calculation, it will not be possible to  reuse  this  space  for  other
  821. calculations without reloading the file defining "longList", or loading
  822. other files instead.
  823.  
  824.  
  825. 9.11 Pattern bindings and irrefutable patterns
  826. ----------------------------------------------
  827. Another useful way of defining variables uses `pattern bindings'  which
  828. are equations of the form:
  829.  
  830.                         pat = rhs
  831.  
  832. where the expression on the left hand side is a pattern as described in
  833. section 9.1.  As a simple example of  pattern  bindings,  here  is  one
  834. possible definition for the function "head"  which  returns  the  first
  835. element in a list of values:
  836.  
  837.     head xs  =  x  where  (x:ys) = xs
  838.  
  839. [The definition "head (x:_) = xs"  used  in  the  standard  prelude  is
  840. slightly more efficient, but otherwise equivalent.]
  841.  
  842. [ASIDE: Note that pattern bindings are treated quite  differently  from
  843. function bindings (of which the variable declarations described in  the
  844. last section are a special case).  There are two situations in which an
  845. ambiguity may occur; i.e. if the left hand side of  an  equation  is  a
  846. simple variable or an (n+k) pattern of the kind  described  in  section
  847. 9.1.  In both cases, these are treated as function bindings, the former
  848. being a variable declaration whilst the latter will  be  treated  as  a
  849. definition for the operator symbol (+).]
  850.  
  851. Pattern bindings are often useful for defining functions which we might
  852. think of as `returning more  than  one  value'  --  although  they  are
  853. actually packaged up in a single value such as a tuple.  As an example,
  854.  
  855.  
  856.                                       33
  857.  
  858.  
  859.  
  860.  
  861. Introduction to Gofer         9.11 Pattern bindings and irrefutable patterns    
  862.  
  863.  
  864. consider the function "span" defined in the standard prelude.
  865.  
  866.     span :: (a -> Bool) -> [a] -> ([a],[a])
  867.  
  868. If xs is a list of values and p is a predicate, then span p xs  returns
  869. the pair of lists (ys,zs) such that ys++zs == xs, all of  the  elements
  870. in ys satisfy the predicate p and the first  element  of  zs  does  not
  871. satisfy p.  A suitable definition, using a pattern  binding  to  obtain
  872. the two lists resulting  from  the  recursive  call  to  "span"  is  as
  873. follows:
  874.  
  875.     span p []               = ([],[])
  876.     span p xs@(x:xs')
  877.                 | p x       = let (ys,zs) = span p xs' in (x:ys,zs)
  878.                 | otherwise = ([],xs)
  879.  
  880.  
  881. For consistency with the lazy evaluation strategy used  in  Gofer,  the
  882. right hand side of a pattern binding is not evaluated until  the  value
  883. of one of the  variables  bound  by  that  pattern  is  required.   The
  884. definition:
  885.  
  886.     (0:xs) = [1,2,3]
  887.  
  888. will not cause any errors when it is loaded into Gofer, but will  cause
  889. an error if we attempt to evaluate the variable xs:
  890.  
  891.     ? xs
  892.     {v120 [1, 2, 3]}
  893.     (11 reductions, 46 cells)
  894.     ?
  895.  
  896. The variable name "v120" appearing in this expression is the name of  a
  897. function called a `conformality check' which is  defined  automatically
  898. by Gofer to ensure that the value on the right hand side of the pattern
  899. binding conforms with the pattern on the left.
  900.  
  901. Compare this  with  the  behaviour  of  pattern  matching  in  function
  902. definitions such as:
  903.  
  904.     ? example [1] where example (0:xs) = "Hello"
  905.     {v126 [1]}
  906.     (4 reductions, 22 cells)
  907.     ?
  908.  
  909. where  the  equivalent  of  the  conformality  check  is  carried   out
  910. immediately even if none of the values of the variables in the  pattern
  911. are actually required.  The reason for  this  difference  is  that  the
  912. arguments supplied to a function must be evaluated to  determine  which
  913. equation in the definition of the function should be used.   The  error
  914. produced by the example above was caused by the fact that the  argument
  915. [1] does not match the pattern used in the equation defining  "example"
  916. (represented by an internal Gofer function called "v126").
  917.  
  918. A different kind of behaviour can be obtained using a  pattern  of  the
  919. form ~pat, known as an irrefutable (or lazy) pattern.  This pattern can
  920.  
  921.  
  922.                                       34
  923.  
  924.  
  925.  
  926.  
  927. Introduction to Gofer         9.11 Pattern bindings and irrefutable patterns    
  928.  
  929.  
  930. initially be matched against any value, delaying the  check  that  this
  931. value does indeed match pat until the value of  one  of  the  variables
  932. appearing in it is required.  The basic idea (together with the  method
  933. used to implement irrefutable patterns in Gofer) is illustrated by  the
  934. identity:
  935.  
  936.     f ~pat = rhs     is equivalent to     f v = rhs where pat=v
  937.  
  938. The following examples, based  very  closely  on  those  given  in  the
  939. Haskell report [5], illustrate the use of  irrefutable  patterns.   The
  940. variable "undefined" used in these examples is included in the standard
  941. prelude  and  causes  a  run-time  error  each  time  it  is  evaluated
  942. (technically speaking, it represents the bottom element of the relevant
  943. semantic domain, and is the only value having all possible types):
  944.  
  945.    (\ (x,y) -> 0) undefined = {undefined}
  946.    (\~(x,y) -> 0) undefined = 0
  947.  
  948.    (\ [x] -> 0) [] = {v113 []}
  949.    (\~[x] -> 0) [] = 0
  950.  
  951.    (\~[x, (a,b)] -> x) [(0,1),undefined] = {undefined}
  952.    (\~[x,~(a,b)] -> x) [(0,1),undefined] = (0,1)
  953.  
  954.    (\ (x:xs) -> x:x:xs) undefined = {undefined}
  955.    (\~(x:xs) -> x:x:xs) undefined = {undefined}:{undefined}:{undefined}
  956.  
  957. Irrefutable patterns are not used very frequently,  although  they  are
  958. particularly convenient in some situations (see  section  12  for  some
  959. examples).  Be careful not to use irrefutable patterns where  they  are
  960. not appropriate.  An attempt to define a map function "map'" using:
  961.  
  962.     map' f ~(x:xs) = f x : map' f xs
  963.     map' f []      = []
  964.  
  965. turns out to be equivalent to the definition:
  966.  
  967.     map' f ys  =  f x : map f xs where (x:xs) = ys
  968.  
  969. and will not behave as you might have intended:
  970.  
  971.     ? map' ord "abc"
  972.     [97, 98, 99, {v124 []}, {v124 []}, {v^C{Interrupted!}
  973.     (35 reductions, 159 cells)
  974.     ?
  975.  
  976.  
  977. 9.12 Type declarations
  978. -----------------------
  979. The type system used in Gofer is sufficiently powerful to enable  Gofer
  980. to determine the type of any function without the need to  declare  the
  981. types of the its arguments and return  value  as  in  some  programming
  982. languages.  Despite this, Gofer allows the use of type declarations  of
  983. the form:
  984.  
  985.                 var1, ..., varn :: type
  986.  
  987.  
  988.                                       35
  989.  
  990.  
  991.  
  992.  
  993. Introduction to Gofer         9.12 Type declarations                            
  994.  
  995.  
  996. which enable to  programmer  to  declare  the  intended  types  of  the
  997. variables var1,  ...,  varn  defined  in  either  function  or  pattern
  998. bindings.   There  are  a  number  of  benefits   of   including   type
  999. declarations of this kind in a program:
  1000.  
  1001.   o  Documentation: The  type  of  a  function  often  provides  useful
  1002.      information about the way in which a function is  to  be  used  --
  1003.      including the number and order of its arguments.
  1004.  
  1005.   o  Restriction: In some situations, the type of a  function  inferred
  1006.      by Gofer is  more  general  than  is  required.   As  an  example,
  1007.      consider the following function, intended to act as  the  identity
  1008.      on integer values:
  1009.  
  1010.          idInt x  =  x
  1011.  
  1012.      Without an explicit type declaration, Gofer treats  "idInt"  as  a
  1013.      polymorphic function of type a -> a and does not treat  expression
  1014.      such as "idInt 'A'" as a type error.  This problem can  be  solved
  1015.      by using an explicit type declaration  to  restrict  the  type  of
  1016.      "idInt" to a particular instance of the polymorphic type a -> a:
  1017.  
  1018.          idInt :: Int -> Int
  1019.  
  1020.      Note that an a declaration such as:
  1021.  
  1022.          idInt :: Int -> a
  1023.  
  1024.      is not a valid type for the function "idInt"  (the  value  of  the
  1025.      expression "idInt 42" is an  integer  and  cannot  be  treated  as
  1026.      having an arbitrary type, depending  on  the  value  of  the  type
  1027.      variable "a"), and hence will not be accepted by Gofer.
  1028.  
  1029.   o  Consistency check: As illustrated above, declared types are always
  1030.      checked against the definition of a value to make sure  that  they
  1031.      are compatible.   Thus  Gofer  can  be  used  to  check  that  the
  1032.      programmers intentions (as described  by  the  types  assigned  to
  1033.      variables  in  type  declarations)   are   consistent   with   the
  1034.      definitions of those values.
  1035.  
  1036.   o  Overloading: Explicit type declarations can be  used  to  solve  a
  1037.      number  of  problems  associated  with  overloaded  functions  and
  1038.      values.  See section 14 for further details.
  1039.  
  1040.  
  1041.  
  1042.  
  1043.  
  1044.  
  1045.  
  1046.  
  1047.  
  1048.  
  1049.  
  1050.  
  1051.  
  1052.  
  1053.  
  1054.                                       36
  1055.  
  1056.  
  1057.